package com.wanyl.test;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.*;
import java.util.ArrayList;

public class LocalResource implements HttpHandler {
    static String default_page="index.html";
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String url = exchange.getRequestURI().toString();
        if(url.endsWith("/")) url=url+default_page;
        //File f = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile();
        //f=new File(f,"/www/"+url);
        File f=new File("www/"+url);
        System.out.println(f.getPath().toString());
        if(!f.exists()){
            exchange.sendResponseHeaders(404,0);
            exchange.getResponseBody().write("404 Not Found".getBytes("UTF-8"));
            exchange.close();
            return;
        }

        if(f.isDirectory()){
            exchange.getResponseHeaders().add("Location",url+"/"+default_page);
            exchange.sendResponseHeaders(302,0);
            exchange.close();
            return;
        }

        ArrayList b = new ArrayList();

        FileInputStream in = new FileInputStream(f);
        exchange.sendResponseHeaders(200,0);
        exchange.getResponseHeaders().add("Content-Type", "javascript; charset=utf-8");
        OutputStream dd = exchange.getResponseBody();
        int len=4096;
        byte[] data=new byte[len];
        int readline;
        System.out.println("正在写入缓冲");

        while (( readline = in.read(data)) > 0) {
//                    System.out.println("准备写入"+readline);

            dd.write(data,0,readline);
//                    dd.flush();
//            if (readline < len) {
//                        System.out.println("跳出循环");
//                break;}
//                    System.out.println("发送中");
        }
        System.out.println("完成");
        exchange.close();

    }
}
